﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FindFile
{
    class InitialCharactersNameMatcher : INameMatcher
    {
        internal InitialCharactersNameMatcher(IEnumerable<PhysicalFile> editableItems)
        {
            _physicalFiles = editableItems;
        }

        #region INameMatcher members
        List<NameMatch> INameMatcher.Match(string matchString)
        {
            matchString = matchString.Trim();
            if (String.IsNullOrEmpty(matchString))
            {
                return new List<NameMatch>();
            }

            List<NameMatch> matches = new List<NameMatch>(50);
            foreach (PhysicalFile editableItem in _physicalFiles)
            {
                if (editableItem.Name.StartsWith(matchString, StringComparison.CurrentCultureIgnoreCase))
                {
                    NameMatch match = new NameMatch(editableItem, CountUpFromZeroTo(matchString.Length - 1));
                    matches.Add(match);
                }
            }

            matches.Sort(new Comparison<NameMatch>(NameComparison));
            return matches;
        }

        static int NameComparison(NameMatch x, NameMatch y)
        {
            return x.Name.CompareTo(y.Name);
        }

        private IEnumerable<int> CountUpFromZeroTo(int number)
        {
            for (int i = 0; i <= number; i++)
            {
                yield return i;
            }
        }
        #endregion

        readonly IEnumerable<PhysicalFile> _physicalFiles;
    }
}
